/**
 * 子账号管理
 */
<template>
  <div>
    <div  >
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right" class="margin-t10">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>子账号管理</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="boxBlock"> 
         <div class="serachTop">   
          <!-- 搜索筛选 -->
          <el-form :inline="true" :model="formInline" class="user-search">
            <el-form-item >
              <el-input
                size="small"
                v-model="formInline.parentUserId"
                placeholder="请输入所有者ID"
                type="number"

                clearable
              ></el-input>
            </el-form-item> 
             
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="search"
                >搜索</el-button
              > 
              <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                @click="add()"
                >新增</el-button
              >
            </el-form-item> 
          </el-form>  
         </div>     
      
      <!--列表-->
      <div class="ra_box">  
        <el-table
          size="small"
          :data="listData"
          highlight-current-row
          v-loading="loading"
          element-loading-text="拼命加载中"
          style="width: 100%"
          v-if="listData" 
        >
          <!-- <el-table-column type="selection" width="55"> </el-table-column>  -->
          <el-table-column
            prop="userId"
            label="用户ID"
            show-overflow-tooltip
            width="140"
          >
          </el-table-column>
          <el-table-column
            prop="parentUserId"
            label="所有者ID"
            show-overflow-tooltip
            width="140"
          >
          </el-table-column>
          
          <el-table-column prop="loginName" label="登录名称"   width="160"> </el-table-column>
          <!-- <el-table-column prop="userName" label="用户昵称"  width="130" show-overflow-tooltip> </el-table-column>  -->
          <el-table-column prop="userType" label="用户类型"  width="160" show-overflow-tooltip> 
            <template slot-scope="scope" >
              <div>
                {{
                  scope.row.userType == '00'
                    ? "管理员"
                    : scope.row.userType == '01'?'会员':scope.row.userType == '02'?'IAM用户':'-'
                }}
              </div>
              <!-- (00管理员01会员02IAM用户) -->
            </template> 
          </el-table-column>
          <el-table-column prop="phonenumber" label="手机号码"   width="190" show-overflow-tooltip> </el-table-column>
          <el-table-column prop="email" label="用户邮箱"   width="190" show-overflow-tooltip> </el-table-column>
       
          <el-table-column prop="status" label="帐号状态"   width="160" show-overflow-tooltip> 
            <template slot-scope="scope">             
              <div>
                <el-tag v-if="scope.row.status == 0">
                  正常
                </el-tag> 
                <el-tag type="info" v-if="scope.row.status == 1">停用</el-tag>
              </div>
              <!-- (（0正常 1停用）) -->
            </template> 
          </el-table-column>  
          
          <el-table-column prop="cardBalance" label="卡余额" v-if="userInfo.userType=='01'"   width="130" show-overflow-tooltip> 
            <template slot-scope="scope">
              <div v-if="scope.row.cardBalance>0">
                {{   scope.row.cardBalance  }}   
              </div> 
              <div v-else>0</div>
            </template>  
          </el-table-column>
          <el-table-column prop="count" label="卡Bin"  v-if="userInfo.userType=='01'"   width="130" show-overflow-tooltip> 
            <template slot-scope="scope">
              <div v-if="scope.row.count>0">
                {{   scope.row.count  }}   
              </div> 
              <div v-else>0</div>
            </template>  
          </el-table-column>
          <el-table-column prop="params.refundAmount" label="拒付率"  v-if="userInfo.userType=='01'"   width="130" show-overflow-tooltip>  
            <template slot-scope="scope"> 
              <div v-if="scope.row.params.refuseCount>0&&scope.row.params.transactionCount>0"> 
                {{   (scope.row.params.refuseCount/scope.row.params.transactionCount*100).toFixed(0)  }}   % 
              </div> 
              <div v-else>0</div>
            </template>  
          </el-table-column>

          <el-table-column prop="params.refundAmount" label="退款率"  v-if="userInfo.userType=='01'"   width="130" show-overflow-tooltip>  
            <template slot-scope="scope">
              <div v-if="scope.row.params.refundCount>0&&scope.row.params.transactionCount>0">
                {{   (scope.row.params.refundCount/scope.row.params.transactionCount*100).toFixed(0)  }}   % 
              </div> 
              <div v-else>0</div>
            </template>  
          </el-table-column>

          <el-table-column prop="params.refundAmount" label="退款率"  v-if="userInfo.userType=='01'"   width="130" show-overflow-tooltip>  
            <template slot-scope="scope">
              <div v-if="scope.row.params.refundAmount>0&&scope.row.params.transactionCount>0">  
                {{   (scope.row.params.refundAmount/scope.row.params.transactionCount*100).toFixed(0)  }}   % 
              </div> 
              <div v-else>0</div>
            </template>  
          </el-table-column>  
          <el-table-column prop="remark" label="备注" show-overflow-tooltip> </el-table-column>  
          <el-table-column align="left" label="操作" width="380" fixed="right">
            <template slot-scope="scope"> 
              <el-button size="mini"   type="success" plain @click="edit(scope.row)">
                编辑
              </el-button>  

              <el-button plain style="color:#fff"  size="mini" type="primary"   @click="setRole(scope.row)">
                设置
              </el-button> 
              <el-button size="mini" :type="scope.row.status == 0?'danger':'success'"  plain @click="isVerClick(scope.row)" > 
                 <label v-if="scope.row.status == 1"  >开启</label>
                 <label v-if="scope.row.status == 0"  >关闭</label>
              </el-button> 
              <el-button size="mini"   plain 
              @click="verArry.includes('/api/iam/deleteIam')?verDelShow(scope.row):clickDel(scope.row)" 
                style="color: #f74e4e;">
                删除
              </el-button> 
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <Pagination
        v-bind:child-msg="pageparm"
        @callFather="callFather"
      ></Pagination>
    </div>
    </div> 

    <!-- 新增 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="addForm.userId?'编辑账号':'新增账号'"
      :visible.sync="addFormVisible"
      width="800px"
      @close="closeDialog"
    > 
      <div>   
        <el-form  
            :model="addForm"
            :rules="rulesAdd"
            ref="addForm"  
            label-width="140px"> 
            <el-form-item label="用户名" prop="username">
              <el-input
                size="small"
                v-model="addForm.username" 
                placeholder="请输入用户名"
                style="width: 300px;"
                :disabled="addForm.userId?true:false"
              ></el-input>
            </el-form-item>
           
            <el-form-item label="密码"  v-if="addForm.userId">
              <el-input
                size="small"
                v-model="addForm.password" 
                placeholder="请输入密码"
                type="password"
                style="width: 300px;" 
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-else>
              <el-input
                size="small"
                v-model="addForm.password" 
                placeholder="请输入密码"
                type="password"
                style="width: 300px;" 
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile"  
               v-if="userInfo.userType == '00' || userInfo.userType=='03'"
              :required="userInfo&&(userInfo.userType == '00' || userInfo.userType=='03')?true:false"
               :rules="[
                { required: true, message: '请输入手机号', trigger: 'blur' }, 
              ]">
              <el-input
                size="small"
                v-model="addForm.mobile" 
                placeholder="请输入手机号"
                style="width: 300px;"
                type="tel"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号"   
               v-else
              >
              <el-input
                size="small"
                v-model="addForm.mobile" 
                placeholder="请输入手机号"
                style="width: 300px;"
                type="tel"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email"  v-if="this.userInfo.userType == '01' || userInfo.userType=='02'">
              <el-input
                size="small"
                v-model="addForm.email" 
                placeholder="请输入邮箱"
                style="width: 300px;"
              ></el-input>
            </el-form-item> 
            
            <el-form-item label="备注" prop="remark" class="wid-7">
              <el-input
                size="small"
                v-model.trim="addForm.remark"
                auto-complete="off"
                type="textarea"
                :rows="5"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
        </el-form>

      </div> 

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="submitForm('addForm')" 
          >提交</el-button
        >
        <!-- :disabled="disabled" -->
      </div>
    </el-dialog>

    <!-- 设置角色 --> 
     <el-dialog
      :close-on-click-modal="false"
      title="设置账号权限"
      :visible.sync="roleVisible"
      width="740px"
      @close="roleVisible=false"
    > 
      <div>   
        <!-- @change="handleCheckedCitiesChange" -->
        <el-checkbox-group v-model="checkList" > 
          <div v-for="(item,index) in roleList"  :key="item.roleId" class="checkItem" >
            <el-checkbox   border  :label="item.roleId" :disabled="index==0?true:false" > 
                <div>{{ item.roleName }} </div> 
                <div class="ptxt"><label style="color: #999;">({{ item.remark }})</label> </div> 
            </el-checkbox>
          </div>
          
        </el-checkbox-group>  
      </div>
      <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="roleVisible=false">取消</el-button> 
          <el-button
            size="small"
            type="primary"
            :loading="loading"
            @click="verArry.includes('/api/iam/addIamRoles')?verShow():submitFormRole('addForm')" 
            >确定</el-button
          >
          <!-- :disabled="disabled" -->
        </div> 
    </el-dialog>  
    <codeChoose ref="codeRef" :fromType="verType" @setParam="getParam"></codeChoose>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";
import {
  setStoreS,
  getStoreS,
  removeStoreS,
  insertCharacter,
  timestampToTime,
  timestampToData,
  timestampSubTime,
  phoneReg,
  emailReg,
  spStr,
} from "../../utils/util";
import {
  baseURL,
  service,
  decrypt,
  reqtoken,
  reqField,
  format,
  getUrl,
  encrypt,
  encryptp,
  reqJson,
  decryptp,
} from "../../api/axiosFun"; 

import { phoneInfo, nation, getPhone, getNation } from "../../utils/cardData";
import Pagination from "../../components/Pagination";
import codeChoose from '@/components/codeChoose.vue'
var validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入正确的手机号'));
  } else {
    // if (this.addForm.mobile !== '') {
    //   this.$refs.addForm.validateField('checkPass');
    // }
    callback();
  }
}; 
export default {
  data() {
    return { 
      userInfo: "",
      loading: false, 
      // rules表单验证
      rulesAdd: {  
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }, 
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }, 
        ],
       
        // 
        email: [ 
          {
            pattern: emailReg,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
      
      }, 
      formInline: {
        pageNum: 1,
        pageSize: 10, 
      },
      listData: "", 
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10,
      },
      addFormVisible:false,
      addForm:{},
      roleVisible:false,
      roleList:[],
      checkList:[],
      curItem:{},
      verType:'',
      headers:{},
      verArry:[]
    };
  },
  // 注册组件
  components: {
    Pagination, 
    codeChoose
  },
  computed: {
    ...mapGetters(["getUser"]),
  },
  watch: {
    getUser(newVal) {
      this.userInfo = JSON.parse(newVal);  
      if(this.userInfo.userType == '00' || this.userInfo.userType=='03'){
        this.rulesAdd.push({
          mobile: [ 
          {
            pattern: phoneReg,
            message: "请输入正确的手机号",
            trigger: "blur", 
            validator: validatePass,
          },
        ],
        })
      } 

    },
  },
  created() {
    if (this.$store.state.user) {
      this.userInfo = JSON.parse(this.$store.state.user); 
      if(this.userInfo&&this.userInfo.verifyApi){
        this.verArry =  this.userInfo.verifyApi.split(',');
      } 
    }
    this.getdata(this.formInline);
    this.getRole();
  },
  methods: { 

    verShow(row){ 
      this.verType = 'role'
      // this.curItem = row
      this.$refs.codeRef.openDialog();   
      return 
    },

    verDelShow(row){ 
      this.verType = 'del'
      this.curItem = row
      this.$refs.codeRef.openDialog();   
      return 
    },

    isVerClick(row){ //开启关闭
      let arrStatus = this.userInfo.verifyApi.split(',') 
      if(arrStatus.includes('/api/iam/disableIam')){ 
        this.verType = 'state'
        this.curItem = row
        this.$refs.codeRef.openDialog();   
        return 
      }else{
        this.setChange(row);
      } 
    },
    // status 
    setChange(row){  
      // disabled禁用  normal启用   
      reqJson('post','/api/iam/disableIam?iamIds='+row.userId+'&&status='+(row.status==1?'normal':'disabled'),{ 
        },{
          headers:{
            ...this.headers
          }
        }) 
      // service
      //   .post("/api/iam/disableIam?iamIds="+row.userId+'&&status='+(row.status==1?'normal':'disabled'))
        .then((res) => {
          this.loading = false;
          if (res.code == 0) { 
            this.$message({
              message: spStr(res.msg, "PhotonPay", ""),
              type: "success",
            });
            this.getdata(this.formInline);
          } else {
             
          }
        })
        .catch((err) => {
          this.$message.error(spStr(err, "PhotonPay", ""));
        });
    },
    setRole(row){  
      this.curItem = row;
      this.checkList = row.params.roleIds;
      this.roleVisible = true; 
    },
    submitFormRole(){    
      reqJson('post',"/api/iam/addIamRoles?iamId="+this.curItem.userId+'&&roleIds='+this.checkList.join(','),{ 
      },{
        headers:{
            ...this.headers
        }
      })  
      // service
      //   .post()
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            this.roleVisible = false; 
            this.$message({
              message: spStr(res.msg, "PhotonPay", ""),
              type: "success",
            });
            this.getdata(this.formInline);
          } else {
            this.roleVisible = false;
          }
        })
        .catch((err) => {
          this.$message.error(spStr(err, "PhotonPay", ""));
        }); 
    },
    getRole(){ 
      service
        .get("/api/iam/getRoles")
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
             this.roleList = res.data;
          } else {
             
          }
        })
        .catch((err) => {
          this.$message.error(spStr(err, "PhotonPay", ""));
        });
  
    },
    clickDel(item){  
      // console.log(item,'item.id'); 
      this.$confirm('确定要删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // service
          // .post("/api/iam/deleteIam?iamIds="+item.userId)

          reqJson('post',"/api/iam/deleteIam?iamIds="+item.userId,{ 
          },{
            headers:{
                ...this.headers
            }
          })  
          
          .then((res) => {
            this.loading = false;
            if (res.code == 0) {
              this.$message({
                message: spStr('删除成功！', "PhotonPay", ""),
                type: "success",
              });
              this.getdata(this.formInline);
            } else {
              this.$message({
                type: "error",
                message: spStr(res.msg, "PhotonPay", ""),
              });
            }
          })
          .catch((err) => {
            this.$message.error(spStr(err, "PhotonPay", ""));
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });


      
    },
    add(){
      this.addFormVisible = true;
      this.addForm = { 
      } 
      this.curItem = { 
      }
    }, 
    edit(item){ 
      this.addForm = {
        ...item,
        username:item.userName,
        password:'',
        mobile:item.phonenumber
      };
      this.curItem = item;
      this.addFormVisible = true;
    },
    getdata(parameter) {
      let url = getUrl(parameter);
      service
        .get("/api/iam/getUserIamList" + url+'&orderByColumn=create_time&isAsc=desc')
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            this.listData = res.rows;
            this.pageparm.currentPage = this.formInline.pageNum;
            this.pageparm.pageSize = this.formInline.pageSize;
            this.pageparm.total = res.total;
          } else {
            this.$message({
              type: "info",
              message: spStr(res.msg, "PhotonPay", ""),
            });
          }
        })
        .catch((err) => {
          this.$message.error(spStr(err, "PhotonPay", ""));
        });
    }, 
    // 分页插件事件
    callFather(parm) {
      this.formInline.pageNum = parm.currentPage;
      this.formInline.pageSize = parm.pageSize;
      this.getdata(this.formInline);
    },
    // 搜索事件
    search() {
      this.getdata(this.formInline);
    },
 
 
     // 关闭编辑、增加弹出框
     closeDialog() { 
      this.addFormVisible = false; 
      // this.$refs.addForm.resetFields();
    }, 
 
    submitForm(type) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {  
          if(this.userInfo.userType == "00" || this.userInfo.userType=='03'){   //管理员端必填手机号
            if(!this.addForm.mobile){
              return   this.$message.error(spStr('手机号必填！', "PhotonPay", ""));
            }
          }else{
            if(!this.addForm.mobile && !this.addForm.email){
              return this.$message.error(spStr('手机号和邮箱必填一项！', "PhotonPay", ""));
            }
          } 
          if(!this.curItem.userId){
            this.curItem = ''
          } 
          // this.loading = true; 
          this.$refs.codeRef.openDialog();   
      }});
    },
    getParam(val,type){ 
      if(type=='state'){  //开启关闭
        this.headers = val
        this.setChange(this.curItem)
      }else if(type=='role'){ //设置 
        this.headers = val
        this.submitFormRole(this.curItem)
      }else if(type=='del'){ //删除 
        this.headers = val
        this.clickDel(this.curItem)
      }else{
     
        if(this.curItem.userId){
          reqJson('post',"/api/iam/updateIam/"+this.curItem.userId,{
            "email": this.addForm.email,
              "mobile": this.addForm.mobile,
              "password":this.addForm.password?encrypt(this.addForm.password):'',
              "remark": this.addForm.remark, 
              "username": this.addForm.username,
          },{
            headers:{
                ...val
            }
          })
      
            .then((res) => {
              this.loading = false;
              if (res.code == 0) {
                this.addFormVisible = false; 
                this.$message({
                  message: spStr(res.msg, "PhotonPay", ""),
                  type: "success",
                });
                this.getdata(this.formInline);
              } else {
                
              }
            })
            .catch((err) => {
              this.$message.error(spStr(err, "PhotonPay", ""));
            });
          }else{  
            reqJson('post',"/api/iam/addIam",{
              ...this.addForm,
              "password":encrypt(this.addForm.password),
            },{
              headers:{
                  ...val
              }
            })
            .then((res) => {
              if (res.code == 0) {
                this.closeDialog("addForm");
                this.loading = false;
                this.$message({
                  message: spStr(res.msg, "PhotonPay", ""),
                  type: "success",
                });
                this.getdata(this.formInline);
              } else {
                this.loading = false;
                this.$message.error(spStr(res.msg, "PhotonPay", ""));
                return;
              }
            })
            .catch((err) => {
              this.$message.error(spStr(err, "PhotonPay", ""));
            }); 

      } 
      }
     
    },

    
    submitFormCard() {
      this.$refs.addCardForm.validate((valid) => {
        if (valid) {
          if (
            this.userInfo.balance < 0 ||
            this.userInfo.balance < this.addCardForm.rechargeAmount
          ) {
            this.$message.error("钱包余额不足，请先充值！");
            return;
          }
          this.addCardForm.dateOfBirth = timestampToData(
            this.addCardForm.dateOfBirth
          );
          this.loading = true;
          if (this.addCardForm.cardType == "share") {
            this.addCardForm.rechargeAmount = 23;
          }
          service
            .post("/api/photon/cardAndHolderApply", this.addCardForm)
            .then((res) => {
              if (res.code == 0) {
                this.closeDialog("addCardForm");
                this.loading = false;
                this.$message({
                  message: spStr(res.msg, "PhotonPay", ""),
                  type: "success",
                });
                this.getdata(this.formInline);
              } else {
                this.loading = false;
                this.$message.error(spStr(res.msg, "PhotonPay", ""));
                return;
              }
            })
            .catch((err) => {
              this.$message.error(spStr(err, "PhotonPay", ""));
            });
        } else {
          return false;
        }
      });
    },
   
 
 
  },
};
</script>

<style scoped>
   .checkItem{
      width: 100%; 
      margin: 10px; 
      height: 60px;  
      display: inline-block;
      align-items: center;
    }
    .checkItem .el-checkbox{
      display: flex;
      align-items: center;
      padding: 10px;
    }
    .checkItem .el-checkbox.is-bordered{
      height: 60px;  
    }
    .checkItemFlex{
      display: flex;
      justify-content: flex-start;
    }
    .checkItemFlex p{
      font-size: 12px;
      white-space:normal
    }
    .ptxt{
      width: 100%; 
      white-space: nowrap;/*强制一行显示*/
      overflow:hidden;/*超出部分隐藏*/
      text-overflow: ellipsis;/*最后添加省略号*/
    }
    
</style>

 
 